/**
 * 表单校验工具函数
 */

/**
 * 验证手机号
 */
export function validatePhone(phone: string): boolean {
  const reg = /^1[3-9]\d{9}$/
  return reg.test(phone)
}

/**
 * 验证邮箱
 */
export function validateEmail(email: string): boolean {
  const reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  return reg.test(email)
}

/**
 * 验证身份证号
 */
export function validateIdCard(idCard: string): boolean {
  // 18位身份证号码正则
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
  if (!reg.test(idCard)) {
    return false
  }

  // 验证校验码
  const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  let sum = 0
  for (let i = 0; i < 17; i++) {
    const char = idCard[i]
    const weight = weights[i]
    if (char && weight !== undefined) {
      sum += parseInt(char) * weight
    }
  }
  const checkCode = checkCodes[sum % 11]
  const lastChar = idCard[17]
  return lastChar ? lastChar.toUpperCase() === checkCode : false
}

/**
 * 验证URL
 */
export function validateUrl(url: string): boolean {
  const reg = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/
  return reg.test(url)
}

/**
 * 验证密码强度（至少8位，包含大小写字母和数字）
 */
export function validatePassword(password: string): boolean {
  const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/
  return reg.test(password)
}

/**
 * 验证用户名（4-16位字母、数字、下划线）
 */
export function validateUsername(username: string): boolean {
  const reg = /^[a-zA-Z0-9_]{4,16}$/
  return reg.test(username)
}

/**
 * 验证数字（整数或小数）
 */
export function validateNumber(value: string): boolean {
  const reg = /^-?\d+(\.\d+)?$/
  return reg.test(value)
}

/**
 * 验证正整数
 */
export function validatePositiveInteger(value: string): boolean {
  const reg = /^[1-9]\d*$/
  return reg.test(value)
}
